package com.qdlc.p2p.biz.service.impl;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;

import com.google.common.base.Splitter;
import com.qdlc.p2p.biz.service.BaseGiveAwardService;
import com.qdlc.p2p.common.constant.UserWineCouponsCategory;
import com.qdlc.p2p.common.enums.EnumWineCouponsIdsType;
import com.qdlc.p2p.dal.dao.NewActivityAwardLogDao;
import com.qdlc.p2p.dal.dao.UserWineCouponsDao;
import com.qdlc.p2p.dal.dao.WineCouponsDao;
import com.qdlc.p2p.dal.dto.NewActivityAwardLog;
import com.qdlc.p2p.dal.dto.User;
import com.qdlc.p2p.dal.dto.UserWineCoupons;
import com.qdlc.p2p.dal.dto.WineCoupons;
import com.qdlc.p2p.dal.model.BaseGiveAwardModel;
import com.qdlc.p2p.dal.model.WineCouponsModel;

/**
 * Created by ygw on 2016/5/6.
 */
@Service("giveUserWineCouponsService")
public class GiveUserWineCouponsServiceImpl implements BaseGiveAwardService {
    private static Logger logger = Logger.getLogger(GiveUserWineCouponsServiceImpl.class);

    @Resource
    private UserWineCouponsDao userWineCouponsDao;

    @Resource
    private WineCouponsDao wineCouponsDao;

    @Resource
    private NewActivityAwardLogDao newActivityAwardLogDao;

    @SuppressWarnings("static-access")
	@Override
    public void giveAward(BaseGiveAwardModel baseGiveAwardModel) {

        //获取用户
        User user = baseGiveAwardModel.getUser();
        if (null == user) {
            return;
        }
        //获取酒券方案
        WineCoupons wineCoupons = wineCouponsDao.find(baseGiveAwardModel.getRuleId());
        if (null == wineCoupons) {
            logger.info("酒券方案不存在，酒券ID:" + baseGiveAwardModel.getRuleId());
            return;
        }
        WineCouponsModel model = WineCouponsModel.instance(wineCoupons);

        // 检测酒券常规属性
        boolean checkResult = model.checkUseModel();
        if (!checkResult) {
            return;
        }
    	int number = model.getNumber();// 数量
    	if ("null".equals(baseGiveAwardModel.getExtMpas()+"")) {// 后台发放
    		// 发放开始
			for (int i = 0; i < number; i++) {
				UserWineCoupons userWineCoupons = new UserWineCoupons(user,
                        model.getName(), model.getAmount(), model.getType(),
                        model.getValidDay(),UserWineCouponsCategory.VERIFY_FULL_BORROW_SUCCESS,0, baseGiveAwardModel.getSourceType());

                // 更新酒券已发放数量
                wineCoupons.setIssueNum(wineCoupons.getIssueNum() + 1);
                wineCouponsDao.update(wineCoupons);
                userWineCouponsDao.save(userWineCoupons);
			}
    	} else {
    		// 根据酒券规则发放
        	// 传过来的参数
        	String timeLimit = baseGiveAwardModel.getExtMpas().get("timeLimit")+"";// 标期限
    		double tenderMoneySum = Double.parseDouble(baseGiveAwardModel.getExtMpas().get("tenderMoneySum")+"");// 当前标当前用户累计投标金额
    		long borrowId = Long.parseLong(baseGiveAwardModel.getExtMpas().get("borrowId")+"");// 标id
            // 规则参数
        	String rulTimeLimit = model.getTimeLimit();// 标期限
        	List<String> timeLimitList = new ArrayList<String>();
    		if (rulTimeLimit.split(",").length > 0) {
        		timeLimitList = Splitter.on(",").splitToList(rulTimeLimit);
        	} else {
        		timeLimitList.add(rulTimeLimit);
        	}
        	double minTenderAmount = model.getMinTenderAmount();// 使用规则-投标最小金额
        	double maxTenderAmount = model.getMaxTenderAmount();// 使用规则-投标最大金额
        	
        	if (timeLimitList.contains(timeLimit)) {// 标期限判断
    			if (minTenderAmount <= tenderMoneySum && tenderMoneySum < maxTenderAmount) {// 投标金额判断
    				// 发放开始
    				for (int i = 0; i < number; i++) {
    					UserWineCoupons userWineCoupons = new UserWineCoupons(user,
    	                        model.getName(), model.getAmount(), model.getType(),
    	                        model.getValidDay(),UserWineCouponsCategory.VERIFY_FULL_BORROW_SUCCESS,borrowId, baseGiveAwardModel.getSourceType());

    	                // 更新酒券已发放数量
    	                wineCoupons.setIssueNum(wineCoupons.getIssueNum() + 1);
    	                wineCouponsDao.update(wineCoupons);
    	                userWineCouponsDao.save(userWineCoupons);
    				}
    			}
    		}
    	}
    }

    /**
     * 发放给单个用户
     * @param baseGiveAwardModel
     */
    @Override
    public void giveSingleUserAward(BaseGiveAwardModel baseGiveAwardModel) {
        UserWineCoupons userWineCoupons = new UserWineCoupons(baseGiveAwardModel.getUser(),
                baseGiveAwardModel.getDescription(), baseGiveAwardModel.getAmount(), (byte)baseGiveAwardModel.getRuleType(),
                baseGiveAwardModel.getValidDay(), UserWineCouponsCategory.VERIFY_FULL_BORROW_SUCCESS,0,EnumWineCouponsIdsType.WINE_EXCHANGE.getValue());
        userWineCoupons =  userWineCouponsDao.save(userWineCoupons);
        if (null != userWineCoupons) {
            NewActivityAwardLog newActivityAwardLog = new NewActivityAwardLog(baseGiveAwardModel.getUser(), baseGiveAwardModel.getSourceType(), baseGiveAwardModel.getAmount(), BaseGiveAwardModel.RULE_TYPE_WINE_COUPONS);
            newActivityAwardLogDao.save(newActivityAwardLog);
        }
    }
}
